﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections.Specialized;

namespace LFractal.TaskModel
{

    public class TaskFactory
    {
        private static Dictionary<string, ITask> taskExecutorTable = null;
        public static string VALUE_KEY_NAME = "NodeValue";
        static TaskFactory()
        {
            taskExecutorTable = new Dictionary<string, ITask>()
            {
                {"download", null},
                {"unzip",null},
                {"execute", new ExecuteProcessTask()}
            };

        }

        public static ITask GetTaskExecutor(string taskName, NameValueCollection oContext)
        {
            string sKey = taskName.ToLower();
            if (taskExecutorTable.ContainsKey(sKey))
            {
                return taskExecutorTable[sKey];
            }

            return null;
        }

        public static bool ExecuteUpgradeRequestResponse(string responseXML)
        {
            XmlDocument oDoc = new XmlDocument();
            oDoc.LoadXml(responseXML);
            string sActionCode = oDoc.SelectSingleNode("/GIUpdateResponse/ActionCode").InnerText.ToLower();
            switch (sActionCode)
            {
                case "upgrade":
                    {
                        //System.Windows.Forms.MessageBox.Show("Got upgrade response: \n" + responseXML);
                        XmlNodeList oTasks = oDoc.SelectNodes("/GIUpdateResponse/Tasks/Task[ @type = 'download']");
                        if (oTasks != null && oTasks.Count > 0)
                        {
                            UpgradeUI oUI = new UpgradeUI();
                            oUI.ShowDialog();
                            // TODO: enable auto-upgrader in future version
                            //foreach (XmlNode T in oTasks)
                            //{
                            //    NameValueCollection oContextData = new NameValueCollection();
                            //    foreach (XmlAttribute A in T.Attributes)
                            //    {
                            //        oContextData.Add(A.Name, A.Value);
                            //    }

                            //    oContextData.Add(VALUE_KEY_NAME, T.InnerText);

                            //    ITask task = GetTaskExecutor(oContextData["type"], oContextData);
                            //    if (task != null)
                            //    {
                            //        task.Execute(oContextData);
                            //    }
                            //}
                        }

                        return true;
                    }
                    break;

                /* as of now, other action code don't matter .... there's only one other code 'none' */
            }// end of switch


            return false;
        }
    }
}
